package com.aaa.member.config;

import com.aaa.member.util.MyRealm;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @fileName:ShiroConfig
 * @description:
 * @author:zz
 * @createTime:2020/11/13 13:56
 * @version:1.0.0
 */
@Configuration
public class ShiroConfig {

    /**
     * 初始化shiro过滤工厂类
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean  shiroFilterFactoryBean(){
        //实例化
        ShiroFilterFactoryBean shiroFilterFactoryBean =new ShiroFilterFactoryBean();
        //设置未经认证的地址访问后跳转的路径
        //shiroFilterFactoryBean.setLoginUrl("/html/login.html");
        //认证成功后跳转的路径
        //shiroFilterFactoryBean.setSuccessUrl("www.baidu.com");
        //访问未授权地址后跳转的页面
        //shiroFilterFactoryBean.setUnauthorizedUrl("");
        // 实例化map 注意，不能使用 hashmap 无序   LinkedHashMap 有序
        Map<String, String>  filterMap  = new LinkedHashMap<>();
        // 和zuul中配置路由一致  anon 放行地址
        //filterMap.put("/ms/news/**","anon");
        //filterMap.put("/cs/carController/**","anon");
        //filterMap.put("/ulactController/userLogin","anon");
        //filterMap.put("/ulactController/userLogin","anon");
        //filterMap.put("/imgs/**","anon");
        //authc 拦截的请求
        filterMap.put("/**","anon");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        //设置SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager());
        return shiroFilterFactoryBean;
    }

    /**
     * 初始化安全管理器
     * @return
     */
    @Bean
    public SecurityManager securityManager(){
        //实例化
        DefaultWebSecurityManager  securityManager =  new
                DefaultWebSecurityManager();
        //设置realm
        securityManager.setRealm(myRealm());
        return securityManager;
    }

    /**
     * 实例化Realm （安全数据的连接桥梁）
     * @return
     */
    @Bean
    public MyRealm myRealm(){
        //实例化
        MyRealm myRealm = new MyRealm();
        //设置校验匹配器
        myRealm.setCredentialsMatcher(credentialsMatcher());
        return myRealm;
    }
    /**
     * 加密算法及类型设置类
     * @return
     */
    @Bean
    public CredentialsMatcher credentialsMatcher(){
        //实例化
        HashedCredentialsMatcher credentialsMatcher =new HashedCredentialsMatcher();
        //设置加密算法
        credentialsMatcher.setHashAlgorithmName("SHA-512");
        //设置hash次数
        credentialsMatcher.setHashIterations(1024);
        return credentialsMatcher;
    }
}
